package com.weitu.base.controller;

import com.weitu.permission.department.entity.Department;
import com.weitu.permission.resource.service.ResourceService;
import com.weitu.permission.user.entity.User;
import com.weitu.util.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiMeng 2017/3/10
 */
@Controller
@RequestMapping(value = "/")
public class IndexController extends BaseController {

    private final ResourceService resourceService;

    @Autowired
    public IndexController(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @RequestMapping(value = "/index")
    public ModelAndView index() {

        Map paramMap = new HashMap();

        ModelAndView modelAndView = new ModelAndView();

        User loginUser = getSessionUser();
        if (null == loginUser) {
            modelAndView.setViewName("redirect:login.shtml");
        } else {
            String name = loginUser.getName();
            String deptId = loginUser.getDepartment().getId();
            paramMap.put("name",name);
            paramMap.put("deptId",deptId);
            paramMap.put("parentId", "0");

            //获取用户菜单
            List<Map> listMenu = resourceService.selectResourcesByUserId(paramMap);
            modelAndView.addObject("listMenu", listMenu);
            modelAndView.setViewName(BASE_JSP_PATH + "index");
        }

        return modelAndView;
    }

    /**
     * 部门切换
     * @param deptId 部门ID
     * @param deptName 部门名称
     * @return 结果
     */
    @ResponseBody
    @RequestMapping(value = "/switchDepartment")
    public AjaxResult switchDepartment(String deptId, String deptName) {

        AjaxResult ajaxResult = new AjaxResult();

        Department department = new Department();
        department.setId(deptId);
        department.setName(deptName);

        User loginUser = getSessionUser();

        loginUser.setDepartment(department);

        Session session = SecurityUtils.getSubject().getSession();

        session.setAttribute("loginUser", loginUser);

        ajaxResult.setSuccess(true);

        ajaxResult.setMessage("切换部门成功！");

        return ajaxResult;
    }
    @RequestMapping(value = "/main")
    public ModelAndView mainView() {

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName(BASE_JSP_PATH + "main");
        return modelAndView;
    }
}
